import { useRequest } from '@/api'
import { TokenManager } from '@/utils/token'
import { UserInfoManager } from '@/utils/userInfo'

// 请求状态错误
export const httpLogError = (error, msg) => {
  error.message = msg
  uni.showToast({
    title: msg,
    icon: 'error',
    duration: 2000
  })
}

// api请求错误
export const requestError = (response) => {
  return new Promise((resolve, reject) => {
    
    const { data } = response
    const msg = `${data.msg}`

    uni.showToast({
      title: msg,
      icon: 'none',
      duration: 2000
    })
    reject(data)
  })
}

// 登录失效
export const throttleToLogin = () => {
  // 清理登录态与缓存的用户信息
  try { TokenManager.removeToken() } catch {}
  try { UserInfoManager.removeUserInfo() } catch {}
 
  try {
    const { useOutsideAppStore } = require('@/store/app')
    const appStore = useOutsideAppStore && useOutsideAppStore()
    appStore && typeof appStore.$reset === 'function' && appStore.$reset()
  } catch {}
  try {
    const { useOutsideCountStore } = require('@/store/count')
    const countStore = useOutsideCountStore && useOutsideCountStore()
    countStore && typeof countStore.$reset === 'function' && countStore.$reset()
  } catch {}
  uni.reLaunch({
    url: `/pages/login/login`
  })
}

// 上传图片
export const uploadImage = () => {
  return new Promise((resolve, reject) => {
    // 选择图片
    uni.chooseImage({
      count: 1, // 默认选择一张图片
      sizeType: ['original', 'compressed'], // 可以选择原图或压缩图
      sourceType: ['album', 'camera'], // 可以选择相册或相机
      success: (chooseResult) => {
        // 选择成功后，上传图片
        const tempFilePath = chooseResult.tempFilePaths[0] // 获取选择的图片路径
        // 上传图片
        uni.uploadFile({
          url: `${import.meta.env.VITE_APP_API_BASEURL}/api.php/api/member/upload`,
          filePath: tempFilePath,
          name: 'file',
          header: {
            'Content-Type': 'multipart/form-data',
            token: TokenManager.getToken(),
            // token: 'c134ca7ed1e24371100bef9e74f45b7c13305dbbfb251b9a3e6be59c139d57d3'
          },
          success: (uploadResult) => {
            // 上传成功
            const data = JSON.parse(uploadResult.data)
            if (data.code === 200) {
              resolve(data) // 修改这里，返回服务器响应而不是本地文件路径
            } else {
              uni.showToast({
                title: `${data.msg}`,
                icon: 'none',
                duration: 2000
              })
              reject(data)
            }
          },
          fail: (error) => {
            console.error('上传失败:', error)
            reject(error)
          }
        })
      },
      fail: (error) => {
        console.error('选择图片失败:', error)
        reject(error)
      }
    })
  })
}

export const getPrice = async (submitInfo) => {
  const { API_ORDER_PRICE } = useRequest()
  const enumPrice = {
    num: '基础数量',
    base_num_price: '基础数量价格',
    extra_num_multiple: '额外数量倍数',
    extra_num_multiple_price: '额外数量倍数价格',
    base_weight: '基础重量',
    base_weight_price: '基础重量价格',
    extra_weight_multiple: '额外重量倍数',
    extra_weight_multiple_price: '额外重量倍数价格'
  }

  const priceInfoList = ref([])
  const priceInfo = ref({})
  const res = await API_ORDER_PRICE({
    num: submitInfo.num,
    weight: submitInfo.weight,
    tip: submitInfo.tip,
    goods_price: submitInfo.goods_price,
    type: submitInfo.type,
    // cost: submitInfo.cost,
    tenant_id: 8
  })
  if (res.code === 200) {
    priceInfo.value = res.data
    for (const i in res.data.rule) {
      priceInfoList.value.push({
        name: enumPrice[i],
        keyValue: i,
        price: res.data.rule[i]
      })
    }
  }

  return {
    priceList: priceInfoList.value,
    priceObj: priceInfo.value
  }
}
